package com.wits.platform.service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Component;

import com.wits.platform.common.utils.DateUtil;
import com.wits.platform.common.utils.PageUtil;
import com.wits.platform.dao.MmrUserRoleDao;
import com.wits.platform.dao.UserDao;
import com.wits.platform.entity.MmrUserRole;
import com.wits.platform.entity.MmrUserRolePK;
import com.wits.platform.entity.User;
import com.wits.platform.web.mvc.PageParam;

@Component
public class UserService {

	@Resource
	private UserDao userDao;
	
	@Resource
	private MmrUserRoleDao mmrUserRoleDao;

	
	public Page<User> findPage(Map<String, Object> filterParams,PageParam page) {
		PageRequest pageRequest = PageUtil.buildPageRequest(page);
		Specification<User> spec = PageUtil.buildSpecification(User.class,filterParams);
		return userDao.findAll(spec, pageRequest);
	}

	public User save(User command) {
		return userDao.save(command);
	}

	public void delete(String id) {
		userDao.delete(id);

	}

	public void deleteInBatch(String ids) {
		mmrUserRoleDao.deleteByUserIds(ids);
		userDao.deleteInBatch(ids);
	}

	public void update(User command) {
		userDao.save(command);

	}

	public User getOne(String id) {
		return userDao.findOne(id);
	}

	public void saveCascade(User user) {
		List<String> roleIds=user.getRoleIds();
		user=this.save(user);
		if(roleIds !=null && roleIds.size()>0){
			for(String roleId :roleIds){
				if(StringUtils.isNotEmpty(roleId)){
					mmrUserRoleDao.save(new MmrUserRole(new MmrUserRolePK(user.getUserId(),roleId)));
				}
			}
		}
	}

	public void updateCascade(User user) {
		mmrUserRoleDao.deleteByUserId(user.getUserId());
		this.saveCascade(user);
	}

	public void updateEnable(String id, String isEnable) throws Exception{
		userDao.updateField(User.class, id,"isEnable", isEnable);
	}

	public void updateLoginStatus(String id, String ipAddr) throws Exception{
		Map<String,Object> map=new HashMap<String,Object>();
		map.put("ipLogin", ipAddr);
		map.put("dateLogin", DateUtil.getNow());
		userDao.updateField(User.class, id,map);
	}
	
	/**判断用户是否已经存在*/
	public boolean isExist(User user) {
		return userDao.isExist(user);
	}
	
	public List<User> findAllStudent() {
		Map<String, Object> parameters = new HashMap<String, Object>();
		parameters.put( "EQ_usertype", "stu" );
		Specification<User> spec = PageUtil.buildSpecification( User.class, parameters);
		
		return (List<User>) userDao.findAll( spec );
	}
	
	public List<User> findAllTeacherAndStudent() {
		return (List<User>) userDao.findAllTeacherAndStudent();
	}
}
